home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C09 / Cpptime.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.6 KB  |  82 lines

  1. //: C09:Cpptime.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // A simple time class
  7. #ifndef CPPTIME_H
  8. #define CPPTIME_H
  9. #include <ctime>
  10. #include <cstring>
  11.  
  12. class Time {
  13.   std::time_t t;
  14.   std::tm local;
  15.   char asciiRep[26];
  16.   unsigned char lflag, aflag;
  17.   void updateLocal() {
  18.     if(!lflag) {
  19.       local = *std::localtime(&t);
  20.       lflag++;
  21.     }
  22.   }
  23.   void updateAscii() {
  24.     if(!aflag) {
  25.       updateLocal();
  26.       std::strcpy(asciiRep,std::asctime(&local));
  27.       aflag++;
  28.     }
  29.   }
  30. public:
  31.   Time() { mark(); }
  32.   void mark() {
  33.     lflag = aflag = 0;
  34.     std::time(&t);
  35.   }
  36.   const char* ascii() {
  37.     updateAscii();
  38.     return asciiRep;
  39.   }
  40.   // Difference in seconds:
  41.   int delta(Time* dt) const {
  42.     return std::difftime(t, dt->t);
  43.   }
  44.   int daylightSavings() {
  45.     updateLocal();
  46.     return local.tm_isdst;
  47.   }
  48.   int dayOfYear() { // Since January 1
  49.     updateLocal();
  50.     return local.tm_yday;
  51.   }
  52.   int dayOfWeek() { // Since Sunday
  53.     updateLocal();
  54.     return local.tm_wday;
  55.   }
  56.   int since1900() { // Years since 1900
  57.     updateLocal();
  58.     return local.tm_year;
  59.   }
  60.   int month() { // Since January
  61.     updateLocal();
  62.     return local.tm_mon;
  63.   }
  64.   int dayOfMonth() {
  65.     updateLocal();
  66.     return local.tm_mday;
  67.   }
  68.   int hour() { // Since midnight, 24-hour clock
  69.     updateLocal();
  70.     return local.tm_hour;
  71.   }
  72.   int minute() {
  73.     updateLocal();
  74.     return local.tm_min;
  75.   }
  76.   int second() {
  77.     updateLocal();
  78.     return local.tm_sec;
  79.   }
  80. };
  81. #endif // CPPTIME_H ///:~
  82.